<?php
/**
 * Lop nay su dung de hien thi mot dropdrown da cap
 * $name: Ten cua doi tuong dropdown
 * $colValue: Ten cua truong duoc su dung lam value cua dropdown
 * $colLabel: Ten cua truong duoc su dung lam label cua dropdown
 * $data: Mang cac doi tuong duoc su dung de tao len dropdown, moi doi tuong gom 3 truong:
 *          + id: id cua doi tuong, truong nay duoc su dung lam value trong doi tuong dropdown.
 *              Co the thiet lap ten truong nay bang cach set thuoc tinh $colValue cua doi tuong
 *          + value: Truong nay duoc su dung lam label hien thi trong doi tuong dropdown. Co the
 *              thiet lap lai ten truong nay bang cach set thuoc tinh $colLabel cua doi tuong
 *          + children: Chua danh sach cac phan tu con cua doi tuong. Moi phan tu con co cau truc
 *              tuong tu voi phan tu cha.
 * $htmlOptions: Cac tuy chon html khac cua dropdown
 *
 */
class MultiLevelDropDown extends CWidget {
    public $name="category";
    public $colValue = "id";
    public $colLabel = "name";
    public $select;
    public $data=array();
    public $htmlOptions=array();
    public $noneSelect=false;
    public $noneSelectValue="";
    public $noneSelectLabel="";
    public $disableBranch=array();//Hide all brand by parentId

    public function run() {
        $data = $this->flattenArray();
        echo CHtml::dropDownList($this->name, $this->select, $data, $this->htmlOptions);
    }


    /**
     * get all product category and dump it into an array
     * @return Array
     */
    function flattenArray() {
        $flattenArr   = array();
        if($this->noneSelect)
        {
            $flattenArr[$this->noneSelectValue] = $this->noneSelectLabel;
        }

        foreach($this->data as $node) {
            if(!in_array($node->id, $this->disableBranch))
                $this->flattenNode($node, $flattenArr);
        }
        return $flattenArr;
    }

    function flattenNode($node, &$tree, $level=0) {
        for($i=0; $i<$level*4; $i++) $node->{$this->colLabel} = ".".$node->{$this->colLabel};

        if(isset($node->children) && is_array($node->children))
        {
            $children = $node->children;
            unset($node->children);
        }
        
        $tree[$node->{$this->colValue}] = $node->{$this->colLabel};
        if(!empty ($children))
        {
            foreach($children as $child)
            {
                if(!in_array($child->id, $this->disableBranch))
                    $this->flattenNode($child, $tree, $level+1);
            }
        }
    }
}
